package com.sola.mongodb.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.sola.mongodb.entity.User;
import com.sola.mongodb.repository.UserRepository;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

/**
 * 
 * @Package: com.sola.mongodb.controller
 * @author: kangxiaohui
 * @date: 2017年8月12日 下午9:48:26
 *
 */
@RestController
@RequestMapping("/mongo")
@Api("user相关的API,用于测试mongodb")
public class UserController {

	@Autowired
	private UserRepository userRepository;

	@RequestMapping(method = RequestMethod.POST)
	@ApiOperation("增加一个User")
	public User save(@RequestBody User user) {
		return userRepository.save(user);
	}

	@RequestMapping(method = RequestMethod.GET)
	@ApiOperation("查找所有User")
	public List<User> getAll() {
		return userRepository.findAll();
	}
	
	@RequestMapping(method = RequestMethod.PATCH)
	@ApiOperation("修改User")
	public User update(@RequestBody User  user) {
		return userRepository.save(user);
	}
	
	@RequestMapping(method = RequestMethod.DELETE)
	@ApiOperation("刪除User")
	public String delete(@RequestBody String id) {
		try {
			userRepository.delete(id);
			return "success";
		} catch (Exception e) {
			e.printStackTrace();
			return "fail";
		}
	}
	
	@RequestMapping(method = RequestMethod.POST,value = "/name")
	@ApiOperation("通過name查找User")
	public List<User> findByName(@RequestBody String name) {
		return userRepository.findByName(name);
	}
}
